import dotenv from 'dotenv'
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import Redis from 'ioredis'

import { createRouter } from './routes/index'
import { errorHandler } from './middleware/errorHandler'
import { authMiddleware } from './middleware/auth'
import { connectDatabase, disconnectDatabase } from './lib/database'

// 加载环境变量
dotenv.config()

// 创建应用实例
const app = new Koa()
const port = process.env.PORT || 3000

// 创建 Redis 客户端 (可选)
export const redis = process.env.REDIS_URL
    ? new Redis(process.env.REDIS_URL)
    : null

// 简单的日志函数
const log = {
    info: (message: string) => console.log(`[INFO] ${new Date().toISOString()} - ${message}`),
    error: (message: string, error?: any) => console.error(`[ERROR] ${new Date().toISOString()} - ${message}`, error || ''),
    warn: (message: string) => console.warn(`[WARN] ${new Date().toISOString()} - ${message}`)
}

// 简单的日志中间件
app.use(async (ctx, next) => {
    const start = Date.now()
    await next()
    const ms = Date.now() - start
    log.info(`${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`)
})

// 中间件
app.use(errorHandler)
app.use(cors({
    origin: '*',
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}))
app.use(bodyParser({
    enableTypes: ['json', 'form', 'text'],
    jsonLimit: '10mb',
    formLimit: '10mb',
    textLimit: '10mb'
}))

// 认证中间件（仅对需要认证的路由）
app.use(authMiddleware)

// 路由
const router = createRouter()
app.use(router.routes())
app.use(router.allowedMethods())

// 健康检查端点
app.use(async (ctx, next) => {
    if (ctx.path === '/health') {
        ctx.status = 200
        ctx.body = {
            status: 'ok',
            timestamp: new Date().toISOString(),
            uptime: process.uptime()
        }
        return
    }
    await next()
})

// 启动服务器
async function startServer() {
    try {
        // 连接数据库
        await connectDatabase()

        // 测试 Redis 连接 (如果配置了的话)
        if (redis) {
            await redis.ping()
            log.info('✅ Redis connected successfully')
        } else {
            log.info('ℹ️  Redis not configured, skipping connection')
        }

        // 启动服务器
        app.listen(port, () => {
            log.info(`🚀 Server is running on http://localhost:${port}`)
        })
    } catch (error) {
        log.error('❌ Failed to start server:', error)
        process.exit(1)
    }
}

// 优雅关闭
process.on('SIGTERM', async () => {
    log.info('SIGTERM received, shutting down gracefully')
    await disconnectDatabase()
    if (redis) redis.disconnect()
    process.exit(0)
})

process.on('SIGINT', async () => {
    log.info('SIGINT received, shutting down gracefully')
    await disconnectDatabase()
    if (redis) redis.disconnect()
    process.exit(0)
})

// 启动应用
startServer().catch(error => {
    console.error('Failed to start application:', error)
    process.exit(1)
})

export default app
